import { View } from "@tarojs/components";
import React, { useEffect, useState } from "react";
import styles from "./index.module.scss";
import { Checked } from "@nutui/icons-react-taro";
import { Button } from "@nutui/nutui-react-taro";
import Taro, { getCurrentInstance, useDidShow } from "@tarojs/taro";
import { useSetState, useUpdateEffect } from "ahooks";
import { goToPage } from "@/utils/common";
function Success() {
  const [timerId, setTimerId] = useState<any>(null);
  const [timer, setTimer] = useState<number>(0);

  const [pageInfo, setPageInfo] = useSetState({
    title: "操作成功",
    backPageName: "",
    backUrl: "",
    btnTitle: "返回",
    delay: 5,
  });
  const goBack = () => {
    if (!pageInfo.backUrl) {
      Taro.navigateBack({});
    } else {
      goToPage(pageInfo.backUrl);
    }
  };

  useUpdateEffect(() => {
    if (pageInfo.delay) {
      let cDelay = pageInfo.delay;
      setTimer(cDelay);
      let cTimerId = setInterval(() => {
        cDelay -= 1;
        setTimer(cDelay);
      }, 1000);
      setTimerId(cTimerId);
    }
  }, [pageInfo.delay]);

  useUpdateEffect(() => {
    console.log("timer", timer);

    if (timer === 0) {
      clearInterval(timerId);
      goBack();
    }
  }, [timer, timerId]);

  // 对应 onShow
  useDidShow(() => {
    clearInterval(timerId);
    const { router } = getCurrentInstance();
    const { params } = router || {};
    console.log("router", router);
    const {
      title = "操作成功",
      backPageName = "",
      backUrl = "",
      btnTitle = "返回",
      delay = 5,
    } = params as any;
    const deTitle = decodeURIComponent(title);
    const deBackPageName = decodeURIComponent(backPageName);
    const deBtnTitle = decodeURIComponent(btnTitle);
    const deUrl = decodeURIComponent(backUrl);
    setPageInfo({
      title: deTitle,
      backPageName: deBackPageName,
      backUrl: deUrl,
      btnTitle: deBtnTitle,
      delay,
    });
  });

  return (
    <View className={styles["success-wrapper"]}>
      <View className={styles["content"]}>
        <View className={styles["icon"]}>
          <Checked size="5rem" />
        </View>
        <View className={styles["title"]}>{pageInfo.title}</View>
        <View className={styles["desc"]}>
          {`${pageInfo.title}， 将在${timer}S后跳转${
            pageInfo.backPageName ? `至${pageInfo.backPageName}` : ""
          }`}
        </View>
        <View className={styles["btn-wrapper"]}>
          <View className={styles["btn-outer"]}>
            <Button
              block
              type="primary"
              shape="square"
              className={styles["btn"]}
              onClick={() => {
                goBack();
              }}
            >
              {pageInfo.btnTitle}
            </Button>
          </View>
        </View>
      </View>
    </View>
  );
}

export default Success;
